package jobs

import (
	_ "fmt"
	"github.com/dop251/goja"
	"github.com/dop251/goja_nodejs/require"
	"github.com/dop251/goja_nodejs/util"
	"nextFlow/utils"
)

const ModuleName = "ta/jobs"

type H map[string]interface{}

type SuperAgent struct {
	runtime *goja.Runtime
	util    *goja.Object
}

func Require(runtime *goja.Runtime, module *goja.Object) {
	requireWithJobs()(runtime, module)
}

func RequireWithJobs() require.ModuleLoader {
	return requireWithJobs()
}

func requireWithJobs() require.ModuleLoader {
	return func(runtime *goja.Runtime, module *goja.Object) {
		c := &SuperAgent{
			runtime: runtime,
		}

		c.util = require.Require(runtime, util.ModuleName).(*goja.Object)

		o := module.Get("exports").(*goja.Object)
		o.Set("add", func(call goja.FunctionCall) goja.Value {

			v := call.Argument(0).(*goja.Object)

			if playload, ok := goja.AssertFunction(v.Get("playload")); ok {
				playload(call.This, c.runtime.ToValue(H{"code": v.Get("playload").ToString()}))
			}

			return nil
		})
	}
}

func Enable(runtime *goja.Runtime) {
	runtime.Set("jobs", require.Require(runtime, ModuleName))
}

func init() {
	require.RegisterNativeModule(ModuleName, Require)
	utils.Registry.Add(Enable)
}
